<?php

App::import('Sanitize');

class AppController extends Controller
{

    var $layout = 'webapp';
    var $helpers = array('Session', 'Html', 'Form');
    var $components = array('RequestHandler', 'Session', 'Auth', 'Email');

    function beforeFilter()
    {
        $this->Auth->userModel = 'Employee';

        $this->Auth->fields = array(
            'username' => 'primaryemail',
            'password' => 'password'
        );

        /*
         * the statement below disables the auto redirect after successful login, so be sure
         * to redirect the user in the login action to appropriate location.
         */
        $this->Auth->autoRedirect = false;

        $this->Auth->flashElement = "notice";
        $this->Auth->authError = "Please login first.";
        $this->Auth->loginError = "Authentication failed. Invalid email or password.";

        /* check if user has authenticated/validated his email address */
        $this->Auth->userScope = array('Employee.status' => '1');

        if( ($this->Session->read('Auth.Employee.employeetype_id') != Configure::read('employeetype.admin.id')) && $this->params['action'] == 'delete' )
        {
            $this->Session->setFlash(__("Sorry you don't have delete permission.", true), 'notice');
            $this->redirect(APP_URL);
        }

        /* check for proper rights before accessing the admin section */
        if( isset($this->params['prefix']) && $this->params['prefix'] == 'admin' )
        {
            $this->layout = 'webapp_admin';

            if( $this->Session->check('Auth.Employee.id') )
            {
                if( $this->Session->read('Auth.Employee.employeetype_id') != Configure::read('employeetype.admin.id') )
                {
                    $this->Session->setFlash(__("Only CRM admin can access that location.", true), 'notice');
                    $this->redirect($this->Auth->logout());
                }
            }
        }
    }

    /**
     * Checks if the user is able to edit the record or not
     *
     * @param String $model Model name
     * @param String $column Column name (as it appears in the database table)
     * @param Int $id The id of the model
     * @param String $msg Message to display
     * @param Mixed $url Url (where the user will be redirected)
     */
    function canEdit($model, $column, $id, $msg, $url='index')
    {
        $record = $this->{$model}->find(array("$model.id" => $id));
        if( $record[$model][$column] != $this->Auth->user('id') )
        {
            $this->Session->setFlash(__($msg, true), 'notice');
            $this->redirect($url);
        }
    }

}
